<template>
  <div>
    <div class="app-container">
      <h-table-list
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="device_patrol_itemsGroup.records"
        :columns="columns"
        :pagination-info="paginationInfo"
        :form-options="formOptions"
        @size-change="handleSizeChange"
      >
        <ListOpearteButton />
        <template
          slot="userType"
          slot-scope="scope"
        >
          <p>
            <i
              v-if="scope.row.userType == 0"
              class="iconfont deviceicon-dian-0"
            >PC</i>
            <i
              v-if="scope.row.userType == 1"
              class="iconfont deviceicon-dian-1"
            >手机</i>
          </p>
        </template>
        <!-- <template slot="createTime" slot-scope="scope">
          <p>
           {{scope.row.createdTime}}
          </p>
        </template> -->
        <template
          slot="enable"
          slot-scope="scope"
        >
          <p>
            <i
              v-if="scope.row.userType == 0"
              class="iconfont deviceicon-dian-0"
            >停用</i>
            <i
              v-if="scope.row.userType == 1"
              class="iconfont deviceicon-dian-1"
            >启用</i>
          </p>
        </template>
        <template
          slot="operate-column"
          slot-scope="scope"
        >
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </div>
    <DownloadIdentify
      :visible.sync="dialogFormVisible"
      title="巡检项分组"
      @cancel="cancel"
      @update="dialogSubmit"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="分组名称"
          prop="groupName"
        >
          <el-input v-model="ruleForm.groupName" />
        </el-form-item>
        <el-form-item
          label="排序值"
          prop="sortValue"
        >
          <el-input
            v-model="ruleForm.sortValue"
            type="number"
          />
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import waves from '@/directive/waves' // waves directive
import DownloadIdentify from '@/components/FormDialog'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import ListOpearteButton from '@/components/AllButton/button2a'
import tableButton from '@/components/AllButton/button3a'
import data from './const'

export default {
  name: 'DevicePatrolItemsGroup',
  components: {
    DownloadIdentify,
    Pagination,
    tableButton,
    ListOpearteButton
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      loadList: false,
      ruleForm: {
        sortValue: null,
        groupName: ''
      },
      rules: {
        sortValue: [
          { required: true, message: '请输入排序值', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              debugger
              console.log(value, '++value++')
              if (!value) {
                callback(new Error('请输入1-999的整数数'))
                return
              } else if (value < 1 || value > 999) {
                callback(new Error('请输入1-999的整数'))
                return
              } else {
                callback()
              }
            }
          }
        ],
        groupName: [
          { required: true, message: '请填写分组名称', trigger: 'blur' }
        ]
      },

      paginationInfo: {
        sizeChange: e => {
          console.log(e)
        },
        currentChange: e => {
          this.$store.dispatch('device_patrol_itemsGroup/setListSearchParams', {
            current: e
          })
          this.getList(
            Object.assign(
              {},
              this.$store.state.device_patrol_itemsGroup.listSearchParams
            )
          )
        },
        current: 1,
        total: 10
      },
      formOptions: {
        inline: true,
        submitBtnText: '搜索',
        showSearchBtn: false,
        showResetBtn: false,
        searchParamsHandler: () => {
          console.log('搜索')
          this.getList(
            this.$store.state.device_patrol_itemsGroup.listSearchParams
          )
        },
        changevalue: params => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          console.log(params)
          this.$store.dispatch(
            'device_patrol_itemsGroup/setListSearchParams',
            params
          )
        },
        resetBtnCallback: () => {
          this.$store.dispatch(
            'device_patrol_itemsGroup/setListSearchParams',
            {}
          )
          this.getList(
            this.$store.state.device_patrol_itemsGroup.listSearchParams
          )
        },
        forms: [
          // { prop: "groupName", label: "分组" },
          //         { prop: "sortValue", label: "巡检部位" },
          //      { prop: "itemSum", label: "巡检内容" },
          // {
          //   prop: "useDepartmentId",
          //   label: "归属部门",
          //   itemType: "select",
          //   options: [
          //     { value: "", label: "部门1" },
          //     { value: 0, label: "部门2" },
          //     { value: 1, label: "部门3" },
          //   ],
          // },
          // {
          //   prop: "positionsId",
          //   label: "职位",
          //   itemType: "select",
          //   options: [
          //     { value: 0, label: "通用" },
          //     { value: 1, label: "专用" },
          //   ],
          // },
          //  {
          //   prop: "userType",
          //   label: "账号类别",
          //   itemType: "select",
          //   options: [
          //     { value: "0", label: "手机" },
          //     { value: "1", label: "PC" },
          //   ],
          // },
        ]
      },
      columns: [
        { prop: 'groupName', label: '分组名称', width: 250 },

        {
          prop: 'sortValue',
          label: '排序值',
          width: 200
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: 'itemSum',
          label: '组内巡检项数量',
          width: 200
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.itemSum ? deviceInfo.itemSum :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        // { prop: "standard", label: "巡检基准", minWidth: 180 },
        // { prop: "method", label: "巡检方法", minWidth: 180 },
        // {
        //   prop: "itemsSum",
        //   label: "巡检项",
        //   slotName: "items-sum",
        //   minWidth: 180,
        // },
        // { prop: "upPicFlag", label: "上传图片", minWidth: 180,filter:"formatIsNecessary" },
        // { prop: "upVideoFlag", label: "上传视频", minWidth: 180 ,filter:"formatIsNecessary" },
        // {
        //   prop: "createdTime",
        //   label: "创建时间",
        //   minWidth: 180,
        // //  slotName: "createdTime",
        // },
        {
          prop: 'operate',
          label: '操作',
          minWidth: 240,
          slotName: 'operate-column',
          fixed: 'right'
        }
      ],
      tableData: []
    }
  },

  watch: {
    formChange: () => {}
  },
  computed: {
    ...mapState(['device_patrol_itemsGroup', 'app'])
  },
  created() {
    // 初始获取几个基本数据,分别为操作状态,按钮权限等
    (this.formOptions.forms = this.formOptions.forms.map(e => {
      const key = e.prop
      const data = this.$store.state.device_patrol_itemsGroup.listSearchParams
      e.defaultValue = data[key] || ''
      return e
    })),
    // this.submitHandler=this.searchWithParams
    this.$store
      .dispatch(this.$store_url_button, {
        add: this.add,
        export: this.export,
        delete: this.delete,
        edit: this.edit,
        detail: this.detail,
        using: this.using,
        useless: this.useless,
        downloadTemplete: this.downloadTemplete,
        downloadIdentify: this.downloadIdentify
      })
      .then(async() => {
        // await this.$store.dispatch("app/getCodeList", []); //code转码
        this.getList() // 表格数据
      })

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    cancel() {
      this.dialogFormVisible = false
    },
    dialogSubmit() {
      this.$refs['ruleForm'].validate(valid => {
        console.log(this.ruleForm, '+++ this.ruleForm+++')
        if (valid) {
          this.$store
            .dispatch('device_patrol_itemsGroup/saveInfo', this.ruleForm)
            .then(res => {
              this.getList()
              this.dialogFormVisible = false
            })
            .catch(err => {})
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 自定义该业务模块下的按钮方法
    // 自定义该业务模块下的按钮方法
    using(row) {
      this.$store
        .dispatch('device_patrol_itemsGroup/useUserInfo', row.id)
        .then(res => {
          this.getList()
          // this.dialogFormVisible=false
        })
        .catch(err => {})
    },
    useless(row) {
      this.$store
        .dispatch('device_patrol_itemsGroup/uselessUserInfo', row.id)
        .then(res => {
          this.getList()
          // this.dialogFormVisible=false
        })
        .catch(err => {})
    },
    add(row) {
      this.ruleForm = {
        sortValue: null,
        groupName: ''
      }
      this.dialogFormVisible = true
    },
    edit(row) {
      this.ruleForm = JSON.parse(JSON.stringify(row))
      this.ruleForm.sortValue = this.ruleForm.sortValue.toString()
      this.dialogFormVisible = true
    },
    downloadIdentify(row) {
      console.log('下载设备标识卡')
      this.dialogFormVisible = true
    },
    async downloadTemplete(ids) {
      console.log('下载导出模板')
      const download = await this.$store.dispatch(
        'device_patrol_itemsGroup/downloadTemplete'
      )
      // window.open(download.)
      console.log(download)
    },
    delete(row) {
      console.log(row)
      this.$confirm(
        `分组删除后不可恢复，组内数据将移入默认分组确认删除？`,
        '删除分组',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$store
            .dispatch('device_patrol_itemsGroup/deleteDeviceInfo', row.id)
            .then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '删除失败'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    update() {},
    detail(row) {
      console.log(row)

      localStorage.setItem('/device-basic/component/detail/index', row.id)
      this.$router.push('/device-basic/component/detail/index')
    },
    import() {},
    export() {
      console.log('导出')
      this.$store.dispatch('device_patrol_itemsGroup/exportFile')
    },
    // 弹窗的关闭
    cancel() {
      console.log('关闭弹窗')
      this.dialogFormVisible = false
    },
    // 更新弹窗数据
    updateDialog() {
      console.log('更新并关闭弹窗')
      this.dialogFormVisible = false
    },
    // 搜索按钮
    searchWithParams() {
      console.log('搜索')
    },
    async getList(args) {
      // this.listLoading = true
      console.log(args)
      await this.$store.dispatch(
        'device_patrol_itemsGroup/requestDeviceList',
        args
      )
      this.paginationInfo.total = this.$store.state.device_patrol_itemsGroup.total
    },
    handleFilter(args) {
      this.listQuery.page = 1
      this.getList(args)
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
